/**
 *

 * @Author Administrator
 * @Desc Mocker
 * @Date 2020年6月7日
 */
package com.zlyx.easy.mock;

import java.io.File;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.zlyx.easy.core.reflect.ClassBody;
import com.zlyx.easy.core.utils.ClassUtils;
import com.zlyx.easy.core.utils.FileUtils;
import com.zlyx.easy.mock.reader.MockReader;

/**
 * mock代码生成
 *
 * @Author 赵光
 * @Desc ClassMocker
 * @Date 2020年6月7日
 */
public class ClassMocker {

	private static Logger logger = LoggerFactory.getLogger(ClassMocker.class);

	/**
	 * mock指定类
	 * 
	 * @param cls
	 * @return
	 * @throws Exception
	 */
	public static String mock(Class<?> cls) throws Exception {
		ClassBody classBody = MockReader.mock(cls);
		return classBody == null ? null : writeAsFile(classBody, true);
	}

	/**
	 * mock整个项目
	 * 
	 * @param cls
	 * @throws Exception
	 */
	public static void mockAll() throws Exception {
		mock(ClassUtils.getAppPath());
	}

	/**
	 * mock指定路径下所有类
	 * 
	 * @param path
	 * @throws Exception
	 */
	public static void mock(String path) throws Exception {
		mock(path, false);
	}

	/**
	 * mock指定路径下所有类
	 * 
	 * @param path    路径
	 * @param rewrite 是否强制重写文件
	 * @throws Exception
	 */
	public static void mock(String path, boolean rewrite) throws Exception {
		List<String> javaFiles = FileUtils.getJavaFiles(path);
		for (String filePath : javaFiles) {
			ClassBody classBody = MockReader.mock(new File(filePath));
			if (classBody != null && !classBody.getMethods().isEmpty()) {
				writeAsFile(classBody, rewrite);
			}
		}
		logger.info("单元测试文件生成结束");
	}

	/**
	 * 写出为文件
	 *
	 * @param classBody 类对象
	 * @param rewrite   是否强制重写文件
	 * @throws Exception
	 */
	public static String writeAsFile(ClassBody classBody, boolean rewrite) throws Exception {
		return classBody.writeAsFile(ClassUtils.getPath() + "\\src\\test\\java\\", rewrite);
	}
}
